package com.huaao.micropolice.root.controllers;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import com.huaao.micropolice.core.common.page.Page;
import com.huaao.micropolice.core.common.page.Sort;

public class BaseController {
	
	@Autowired
	protected HttpServletRequest request;
	
	public static final String CODE				 = "code";
	
	public static final String MESSAGE			 = "message";
	
	public static final String MESSAGE_SUCCESS   = "操作成功";
	
	public static final String MESSAGE_FAIL	     = "操作失败";
	
	public static final MediaType HTML = new MediaType("text", "html", Charset.forName("UTF-8"));
	
	public static final MediaType JSON = new MediaType("application", "json", Charset.forName("UTF-8"));
	
	public <T> ResponseEntity<T> ajaxModel(MediaType mediaType, T data) {
		HttpHeaders headers = new HttpHeaders();
		if(mediaType != null){
			headers.setContentType(mediaType);
		}
		ResponseEntity<T> response = new ResponseEntity<T>(data, headers, HttpStatus.OK);
		return response;
	}
	
	public Map<String, Object> successMap(){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(CODE, 0);
		map.put(MESSAGE, MESSAGE_SUCCESS);
		return map;
	}
	
	public Map<String, Object> successMap(String message){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(CODE, 0);
		map.put(MESSAGE, message);
		return map;
	}
	
	public Map<String, Object> failMap(){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(CODE, 500);
		map.put(MESSAGE, MESSAGE_FAIL);
		return map;
	}
	public Map<String, Object> failMap(String errorMessage){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(CODE, 501);
		map.put(MESSAGE, MESSAGE_FAIL+":"+errorMessage);
		return map;
	}
	/**
	 * 获取分页信息
	 * @return
	 */
	public Page getPage(){
		Page page = new Page();
		String pageNum = request.getParameter("page");
		if(StringUtils.isNotBlank(pageNum)){
			page.setPageNum(Integer.parseInt(pageNum));
		}
		String pageSize = request.getParameter("rows");
		if(StringUtils.isNotBlank(pageSize)){
			page.setPageSize(Integer.parseInt(pageSize));
		}
		return page;
	}
	
	/**
	 * 获取排序信息
	 * @return
	 */
	public Sort getSort(){
		Sort sort = new Sort();
		String name = request.getParameter("sidx");
		if(StringUtils.isNotBlank(name)){
			sort.setName(name);
		}
		String type = request.getParameter("sord");
		if(StringUtils.isNotBlank(type)){
			sort.setType(type);
		}
		return sort;
	}
	
	/**
	 * 获取操作类型
	 * @return
	 */
	public String getOper(){
		return request.getParameter("oper");
	}
	
	public static Map<String, String> getParameterMap(HttpServletRequest request, String prefix) {
		return getParameterMap(request, prefix, false);
	}
	
	public static Map<String, String> getParameterMap( HttpServletRequest request, String prefix, boolean keyWithPrefix) {
		Validate.notNull(request, "Request must not be null");
		Map<String, String> params = new LinkedHashMap<String, String>();
		if (prefix == null) {
			prefix = "";
		}
		String qs = request.getQueryString();
		Map<String, String[]> queryMap = parseQueryString(qs);
		int len = prefix.length();
		Enumeration paramNames = request.getParameterNames();
		while (paramNames != null && paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			if ("".equals(prefix) || paramName.startsWith(prefix)) {
				String name = keyWithPrefix ? paramName : paramName.substring(len);
				String value = getParameter(request, queryMap, paramName);
				if(!StringUtils.isBlank(value)){
					params.put(name, value);
				}
			}
		}
		return params;
	}
	
	public static Map<String, String[]> parseQueryString(String queryString) {
		if (StringUtils.isBlank(queryString)) {
			return Collections.emptyMap();
		}
		Map<String, String[]> queryMap = new TreeMap<String, String[]>();
		String[] params = StringUtils.split(queryString, '&');
		for (String param : params) {
			int index = param.indexOf('=');
			if (index != -1) {
				String name = param.substring(0, index);
				// name为空值不保存
				if (StringUtils.isBlank(name)) {
					continue;
				}
				String value = param.substring(index + 1);
				try {
					value = URLDecoder.decode(value, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				if (queryMap.containsKey(name)) {
					String[] values = queryMap.get(name);
					queryMap.put(name, ArrayUtils.addAll(values, value));
				} else {
					queryMap.put(name, new String[] { value });
				}
			}
		}
		return queryMap;
	}
	
	public static String getParameter(HttpServletRequest request, Map<String, String[]> queryMap, String name) {
		String[] values = getParameterValues(request, queryMap, name);
		return ArrayUtils.isNotEmpty(values) ? StringUtils.join(values, ',') : null;
	}
	
	public static String getParameter(HttpServletRequest request, String name) {
		String[] values = getParameterValues(request, name);
		return ArrayUtils.isNotEmpty(values) ? StringUtils.join(values, ',') : null;
	}

	public static String[] getParameterValues(HttpServletRequest request, Map<String, String[]> queryMap, String name) {
		Validate.notNull(request, "Request must not be null");
		String[] values = queryMap.get(name);
		if (values == null) {
			values = request.getParameterValues(name);
		}
		return values;
	}

	public static String[] getParameterValues(HttpServletRequest request, String name) {
		Validate.notNull(request, "Request must not be null");
		String qs = request.getQueryString();
		Map<String, String[]> queryMap = parseQueryString(qs);
		return getParameterValues(request, queryMap, name);
	}
}
